﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using log4net;
using CashFlow.Db.Entity;
using CashFlow.Db.DAL;
using SysAdmin._03_Service._00_Db;
using SysAdmin._04_Form._00_Common;

namespace SysAdmin._04_Form._01_Shop
{
    public partial class UpdateShopUserForm : Form
    {
        private static ILog _logger = LogManager.GetLogger(typeof(UpdateShopUserForm));
        private IList<UserInfoEntity> UserList { get; set; } = new List<UserInfoEntity>();
        private IList<UserInfoEntity> ShopUserList { get; set; } = new List<UserInfoEntity>();
        private Timer _timer = new Timer();
        public int ShopManagerUserId { get; set; }

        public UpdateShopUserForm()
        {
            InitializeComponent();
        }

        private void UpdateShopUserForm_Load(object sender, EventArgs e)
        {
            _timer.Interval = 100;
            _timer.Tick += _timer_Tick;
        }

        private void UpdateShopUserForm_Shown(object sender, EventArgs e)
        {
            _timer.Start();
        }

        private void _timer_Tick(object sender, EventArgs e)
        {
            try
            {
                _timer.Stop();
                UserList = UserService.QueryAllChildUsersByUserId(ShopManagerUserId);
                InitTreeView();
                SetSelectedTreeViewItem();
            }
            catch (Exception ex)
            {
                _logger.Error(ex);
                UICommonTool.ShowAlertDialog(ex.Message);
            }
        }

        private void InitTreeView()
        {
            try
            {
                var ui = UserList.Where(x => x.Id == ShopManagerUserId).First();
                var rootNode = new TreeNode(ui.Name);
                rootNode.Tag = ui;
                Queue<string> queue = new Queue<string>();
                queue.Enqueue(ui.InvitationCode);
                UserInfoEntity parentUserInfo = ui;
                List<TreeNode> parentNodes = new List<TreeNode>();
                parentNodes.Add(rootNode);
                var tmpParentNodes = new List<TreeNode>();
                int index = 0;
                while (queue.Count > 0)
                {
                    string invitationCode = queue.Dequeue();
                    var ls = UserList.Where(x => x.ReferenceInvitationCode == invitationCode).ToList();

                    foreach (var item in ls)
                    {
                        var node = new TreeNode(item.Name);
                        node.Tag = item;
                        node.ToolTipText = string.Format("{0} - {1}", item.Name, item.Phone);
                        parentNodes[index].Nodes.Add(node);
                        queue.Enqueue(item.InvitationCode);
                        tmpParentNodes.Add(node);
                    }

                    index++;
                    if (index == parentNodes.Count)
                    {
                        parentNodes.Clear();
                        parentNodes.AddRange(tmpParentNodes.ToArray());
                        tmpParentNodes.Clear();
                        index = 0;
                    }
                }

                treeView1.BeginUpdate();
                treeView1.Nodes.Add(rootNode);
                treeView1.EndUpdate();
            }
            catch (Exception ex)
            {
                _logger.Error(ex);
                UICommonTool.ShowAlertDialog(ex.Message);
            }
        }

        private void SetSelectedTreeViewItem()
        {
            try
            {
                var ls = ShopUserService.QueryAllShopUsers(ShopManagerUserId);
                ShopUserList = ls.Select(x => x.UserInfo).ToList();
                var ls2 = UICommonTool.GetAllTreeNodes(treeView1);
                foreach (TreeNode item in ls2)
                {
                    if (item.Tag != null)
                    {
                        var obj = item.Tag as UserInfoEntity;
                        if (ShopUserList.Count(x => x.Id == obj.Id) > 0)
                        {
                            item.Checked = true;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.Error(ex);
                UICommonTool.ShowAlertDialog(ex.Message);
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                if (UICommonTool.ShowConfirmDialog("确定要更新店铺成员吗？"))
                {
                    var ls = UICommonTool.GetAllTreeNodes(treeView1);
                    var ls2 = ls.Where(x => x.Checked == true).ToList();
                    var ls3 = FilterUserIdList(ls2);
                    var ls4 = ls.Where(x => x.Checked == false).ToList();
                    var ls5 = FilterUserIdList(ls4);
                    bool b = ShopUserService.UpdateShopUser(ShopManagerUserId, ls3, ls5);
                    if (b)
                    {
                        UICommonTool.ShowInfoDialog("更新店铺成员成功！");
                        DialogResult = DialogResult.OK;
                        Close();
                    }
                    else
                    {
                        UICommonTool.ShowAlertDialog("更新店铺成员失败！");
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.Error(ex);
                UICommonTool.ShowAlertDialog(ex.Message);
            }
        }

        private IList<int> FilterUserIdList(IList<TreeNode> ls)
        {
            var ls2 = new List<int>();
            foreach (var item in ls)
            {
                if (item.Tag != null)
                {
                    var obj = item.Tag as ShopInfoEntity;
                    if (obj != null)
                    {
                        ls2.Add(obj.Id);
                    }
                }
            }
            return ls2;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            treeView1.ExpandAll();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            treeView1.CollapseAll();
        }
    }
}
